package com.zhanghu.backendZray.controller.file;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhanghu.backendZray.annotation.MenuNeed;
import com.zhanghu.backendZray.cache.ContextCache;
import com.zhanghu.backendZray.manager.minIO.MinIOManager;
import com.zhanghu.backendZray.manager.role.UserRoleMenuManager;
import com.zhanghu.backendZray.pojo.dto.ApiResponse;
import com.zhanghu.backendZray.pojo.request.OnlyIdRequest;
import com.zhanghu.backendZray.pojo.request.file.FilePageRequest;
import com.zhanghu.backendZray.pojo.request.file.FileUploadRequest;
import com.zhanghu.backendZray.pojo.vo.FileVo;
import com.zhanghu.backendZray.service.FileService;
import com.zhanghu.backendZray.service.TrialRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ZhangDong
 * @date 2024/8/14 14:54
 */
@RestController
@RequestMapping("file")
@RequiredArgsConstructor
@Validated
public class FileController {
    private final MinIOManager manager;
    private final FileService fileService;
    private final UserRoleMenuManager userRoleMenuManager;
    private final TrialRecordService trialRecordService;

    /**
     * 文件上传（目前只支持图片）
     * 前端加了限制，后端还没加
     * 图片加了缩略图生成功能
     *
     * @param request
     * @return
     */
    @MenuNeed(menuName = "file_upload")
    @PostMapping("upload")
    public ApiResponse upload(FileUploadRequest request) {
        // 试用角色文件上传限制
        userRoleMenuManager.trialRoleFileUploadLimit(ContextCache.currentUserId());
        manager.uploadFile(request);
        // 文件上传次数加一
        trialRecordService.fileUploadCountAdd(ContextCache.currentUserId());
        return ApiResponse.ok();
    }

    /**
     * 分页查询
     *
     * @param filePageRequest
     * @return
     */
    @MenuNeed(menuName = "file_list")
    @PostMapping("page")
    public ApiResponse<Page<FileVo>> page(@RequestBody FilePageRequest filePageRequest) {
        Page<FileVo> pageInfo = fileService.page(filePageRequest);
        return ApiResponse.ok(pageInfo);
    }

    /**
     * 删除文件
     */
    @MenuNeed(menuName = "file_list")
    @PostMapping("delete")
    public ApiResponse delete(@RequestBody OnlyIdRequest onlyIdRequest) {
        manager.delete(onlyIdRequest.getId());
        return ApiResponse.ok();
    }
}
